package com.itheima.datastructure.queue;

import java.util.Iterator;

/**
 * @author tantao
 * @version 1.0
 * @description: 用环形数组实现队列
 * @date 2025/9/10 14:35
 */
public class ArrayQueue11<E> implements Queue<E>, Iterable<E> {

    private final E[] array;
    // 头指针_index
    private int head = 0;
    // 尾指针_index （tail指针指向的位置不能存储元素）
    private int tail = 0;

    // 构造方法
    @SuppressWarnings("all")
    public ArrayQueue11(int capacity) {
        array = (E[]) new Object[capacity + 1];
    }

    @Override
    public boolean offer(E value) {
        if (isFull()) {
            return false;
        }
        array[tail] = value;
        tail = (tail + 1) % array.length;
        return true;
    }

    @Override
    public E poll() {
        if (isEmpty()) {
            return null;
        }
        E removed = array[head];
        // 头指针再移动一格
        head = (head + 1) % array.length;
        return removed;


    }

    @Override
    public E peek() {
        if (isEmpty()) {
            return null;
        }
        return array[head];
    }

    @Override
    public boolean isEmpty() {
        return head == tail;

    }

    @Override
    public boolean isFull() {
        //尾指针再移动一格，头指针和尾指针相等，队列为空
        return (tail + 1) % array.length == head;
    }

    @Override
    public Iterator<E> iterator() {

        return new Iterator<E>() {
            //定义一个指针，指向头指针
            int p = head;

            @Override
            public boolean hasNext() {
                return p != tail;
            }

            @Override
            public E next() {
                E value = array[p];
                p = (p + 1) % array.length;
                return value;
            }
        };
    }
}
